<template>
  <view class="container">
    <uni-forms
      label-Position="top"
      v-if="this.approval[0].stepName=='部门负责人' && this.approval[0].uid==this.taskInfo.uid  && this.approval[1].stepName=='分管领导'"
    >
      <uni-forms-item label="选择分管领导" required>
        <view>
          <button @click="clickSelectOne" class="btn-add" v-if="users.length != 0">{{users[0].name}}</button>
        </view>
        <view>
          <button @click="clickSelectOne" class="btn-add" v-if="users.length == 0">{{'选择分管领导'}}</button>
        </view>
      </uni-forms-item>
    </uni-forms>
    <uni-forms label-Position="top" v-if="showMsg">
      <uni-forms-item label="审批意见">
        <uni-easyinput type="textarea" v-model="msg" placeholder="请输入审批意见" autoHeight />
      </uni-forms-item>
    </uni-forms>

    <view style="padding: 20px;"></view>

    <uni-row v-if="typ == 0">
      <uni-col :span="12">
        <button @click="rejectTask()" type="warn">拒绝</button>
      </uni-col>
      <uni-col :span="12">
        <button @click="agreeTask()" type="primary">同意</button>
      </uni-col>
    </uni-row>
  </view>
</template>

<script>
import { websock } from "../../net/websock";
import { shenpiXinjian, getUserList } from "../../net/xinjianfawen";
export default {
  data() {
    return {
      taskid: 0,
      msg: "",
      title: "",
      id: "",
      approvalProcessDataBeanMap: {},
      selectBtnStr: "",
      chengbanBtnStr: "已完成",
      showMsg: true,
      typ: 0, // 0 审批 1承办
      userInfo: {},
      taskInfo: {},
      taskInfo1: [],
      applyInfo: {},
      departList: [],
      departNames: [],
      showSelectDepart: false,
      showSelectOne: false,
      showSelectMany: false,
      users: [],
      usersd: [],
      approval: [],
      selectedDeparts: []
    };
  },
  async onLoad(params) {
    console.log("on load", params);
    this.taskid = params.taskid;
    this.id = params.id;
    this.approvalProcessDataBeanMap = JSON.parse(
      params.approvalProcessDataBeanMap
    );
    this.approval = Array.from(
      Object.values(this.approvalProcessDataBeanMap),
      x => x
    );
    console.log(this.approval[0]);
    this.typ = 0;

    try {
      this.departList = await websock.getDepartList();
      for (let i = 1; i != this.departList.length; i++) {
        this.departNames.push(this.departList[i].name);
      }

      this.userInfo = await websock.getUserInfo();
      console.log("user info", this.userInfo);

      this.taskInfo1 = await getUserList();
      console.log("task info", this.taskInfo1);

      this.taskInfo = await websock.getTaskDetail({ id: this.taskid });
      console.log("task info", this.taskInfo);

      this.typ = this.taskInfo.isChengban;
    } catch (err) {
      console.error(err);
    }
  },
  methods: {
    async agreeTask() {
      this.approvalProcessDataBeanMap = Array.from(
        Object.values(this.approvalProcessDataBeanMap),
        x => x
      );
      console.log(this.approvalProcessDataBeanMap);
      const timestamp = new Date().getTime();
      this.approvalProcessDataBeanMap.forEach(data => {
        // console.log(data.uid);
        console.log(uni.getStorageSync("userInfo").uid);
        if (data.uid == this.taskInfo.uid) {
          data.msg = this.msg;
          data.sta = 1;
          data.ts = timestamp;
        }
      });
      if (
        this.approval[0].stepName == "部门负责人" &&
        this.users.length == 0 &&
        this.approval[0].uid == this.taskInfo.uid &&
        this.approval[1].stepName == "分管领导"
      ) {
        return uni.showToast({ title: "请选择分管领导", icon: "none" });
      } else {
        this.approvalProcessDataBeanMap.forEach(names => {
          if (
            names.stepName == "分管领导" &&
            this.approval[0].uid == this.taskInfo.uid
          ) {
            names.name = this.users[0].name;
            // names.signimg = this.users[0].avatar;
            names.uid = this.users[0].uid;
          }
          this.taskInfo1.data.userList.forEach(item => {
            if (item.uid == names.uid) {
              names.signimg = item.signimg;
            }
          });
        });
      }

      console.log(this.approvalProcessDataBeanMap);
      console.log(this.users);

      let OldObject = this.approvalProcessDataBeanMap.reduce((o, n, i) => {
        o["auditor" + i] = {
          ts: n.ts,
          msg: n.msg,
          sta: n.sta,
          signimg: n.signimg,
          uid: n.uid,
          stepName: n.stepName,
          name: n.name
        };
        return o;
      }, {});
      console.log(OldObject);
      // 新建事项
      const params = {
        id: this.id,
        taskId: this.taskid,
        approvalProcessDataBeanMap: OldObject
      };
      console.log(params);
      // return;
      try {
        const res = await shenpiXinjian(params);
        console.log(res);
        uni.$emit("agree_task", this.taskid);
        uni.showToast({ title: "操作成功" });
        uni.switchTab({ url: "/pages/task/index" });
      } catch (err) {
        console.error(err);
        uni.showToast({ title: "错误" });
      }
    },
    async rejectTask() {
      console.log(this.msg);
      this.approvalProcessDataBeanMap = Array.from(
        Object.values(this.approvalProcessDataBeanMap),
        x => x
      );
      console.log(this.approvalProcessDataBeanMap);
      const timestamp = new Date().getTime();
      this.approvalProcessDataBeanMap.forEach(data => {
        console.log(data.uid);
        console.log(uni.getStorageSync("userInfo").uid);
        // console.log(uni.getStorageSync("loginUserInfo").uid);
        if (data.uid == this.taskInfo.uid) {
          data.msg = this.msg;
          data.sta = 2;
          data.ts = timestamp;
        }
      });
      console.log(this.approvalProcessDataBeanMap);
      if (
        this.approval[0].stepName == "部门负责人" &&
        this.users.length !== 0
      ) {
        return uni.showToast({
          title: "拒绝审批请不要选择分管领导",
          icon: "none"
        });
      }
      let OldObject = this.approvalProcessDataBeanMap.reduce((o, n, i) => {
        o["auditor" + i] = {
          ts: n.ts,
          msg: n.msg,
          sta: n.sta,
          signimg: n.signimg,
          uid: n.uid,
          stepName: n.stepName,
          name: n.name
        };
        return o;
      }, {});
      console.log(OldObject);
      // 新建事项
      const params = {
        id: this.id,
        taskId: this.taskid,
        approvalProcessDataBeanMap: OldObject
      };
      console.log(params);
      try {
        const res = await shenpiXinjian(params);
        console.log(res);
        // uni.$emit("agree_task", this.taskid);
        uni.$emit("reject_task", this.taskid);
        uni.showToast({ title: "操作成功" });
        uni.switchTab({ url: "/pages/task/index" });
      } catch (err) {
        console.error(err);
        uni.showToast({ title: "错误" });
      }
    },
    async confirmTask() {
      try {
        let departs = [];
        if (this.selectedDeparts.length > 0) {
          for (let i = 0; i != this.selectedDeparts.length; i++) {
            departs.push({
              departId: this.departList[this.selectedDeparts[i] + 1].id,
              departName: this.departList[this.selectedDeparts[i] + 1].name,
              departLingdao: this.departList[this.selectedDeparts[i] + 1]
                .zhijie_lingdao,
              departLingdaoName: this.departList[this.selectedDeparts[i] + 1]
                .zhijie_lingdao_name
            });
          }
        }
        await websock.confirmTask({
          id: this.taskid,
          msg: this.msg,
          users: this.users,
          departs
        });
        uni.$emit("confirm_task", this.taskid);
        uni.showToast({ title: "操作成功" });
        uni.switchTab({ url: "/pages/task/index" });
      } catch (err) {
        console.error(err);
        uni.showToast({ title: "错误" });
      }
    },
    clickSelectMany() {
      uni.navigateTo({
        url: "getContactList?selectedUsers=" + JSON.stringify(this.users || []),
        events: {
          contactList: data => {
            console.log("select peitong", data);
            this.users = data.contactList;
          }
        }
      });
    },
    clickSelectOne() {
      uni.navigateTo({
        url:
          "/pages/common/contactSelect?selectedUsers=" +
          JSON.stringify(this.users || []) +
          "&isSingle=1",
        events: {
          contactList: data => {
            console.log("select peitong", data);
            this.users = data.contactList;
          }
        }
      });
    },
    departsChange(e) {
      console.log("departs change");
      this.selectedDeparts = e.detail.value;
    }
  }
};
</script>

<style>
@import url("../common/common.css");
</style>
